package com.info.zhiduoduo.weixin.service;

import com.baomidou.mybatisplus.mapper.Condition;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.info.zhiduoduo.common.configs.UploadPathConfig;
import com.info.zhiduoduo.common.configs.ZddUrlConfig;
import com.info.zhiduoduo.common.constants.Constants;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.constants.marketingcooperative.MarketingCooperativeRecordState;
import com.info.zhiduoduo.common.constants.marketingcooperative.MarketingCooperativeState;
import com.info.zhiduoduo.common.constants.system.UserType;
import com.info.zhiduoduo.common.exception.Asserts;
import com.info.zhiduoduo.common.formbean.BaseSimpleFormBean;
import com.info.zhiduoduo.common.utils.DateUtil;
import com.info.zhiduoduo.common.utils.EasyExcelUtil;
import com.info.zhiduoduo.common.utils.NumberUtil;
import com.info.zhiduoduo.common.utils.QrcodeUtil;
import com.info.zhiduoduo.common.utils.StringUtil;
import com.info.zhiduoduo.core.service.CoreMarketingCooperativeService;
import com.info.zhiduoduo.core.service.WxPartnerMessageService;
import com.info.zhiduoduo.repository.dto.marketingcooperative.*;
import com.info.zhiduoduo.repository.entity.company.CompanyAccount;
import com.info.zhiduoduo.repository.entity.marketingcooperative.*;
import com.info.zhiduoduo.repository.entity.partner.PartnerAccount;
import com.info.zhiduoduo.repository.mapper.marketingcooperative.MarketingCooperativeCompanyFormMapper;
import com.info.zhiduoduo.repository.mapper.marketingcooperative.MarketingCooperativeMapper;
import com.info.zhiduoduo.repository.mapper.marketingcooperative.MarketingCooperativePartnerPosterMapper;
import com.info.zhiduoduo.repository.mapper.marketingcooperative.MarketingCooperativePosterConfigMapper;
import com.info.zhiduoduo.repository.mapper.marketingcooperative.MarketingCooperativeRecordMapper;
import com.info.zhiduoduo.weixin.formbean.marketingcooperative.DealMarketingCooperativeRecordFormBean;
import com.info.zhiduoduo.weixin.formbean.marketingcooperative.GeneratePartnerPosterFormBean;
import com.info.zhiduoduo.weixin.formbean.marketingcooperative.MarketingCooperativeNoteFormBean;
import com.info.zhiduoduo.weixin.formbean.marketingcooperative.MarketingCooperativePartnerListFormBean;
import com.info.zhiduoduo.weixin.formbean.marketingcooperative.MarketingCooperativeRecordListFormBean;
import com.info.zhiduoduo.weixin.formbean.marketingcooperative.PartnerPosterFormFormBean;
import com.info.zhiduoduo.weixin.formbean.marketingcooperative.VerifyMarketingCooperativeRecordFormBean;
import com.info.zhiduoduo.weixin.formbean.partner.PartnerMarketingCooperativeRecordFormBean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class MarketingCooperativeService {

	@Autowired
	WxPartnerMessageService wxPartnerMessageService;
	@Autowired
	CoreMarketingCooperativeService coreMarketingCooperativeService;

	@Resource
	MarketingCooperativeMapper marketingCooperativeMapper;
	@Resource
	MarketingCooperativeRecordMapper marketingCooperativeRecordMapper;
	@Resource
	MarketingCooperativePosterConfigMapper marketingCooperativePosterConfigMapper;
	@Resource
	MarketingCooperativePartnerPosterMapper marketingCooperativePartnerPosterMapper;
	@Resource
	MarketingCooperativeCompanyFormMapper marketingCooperativeCompanyFormMapper;

	@Autowired
	ZddUrlConfig zddUrlConfig;
	@Autowired
	UploadPathConfig uploadPathConfig;

	public MarketingCooperative create(int partnerid, int compid) {
		// 是否需要验证企业是否开通合销云？
		CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", compid));
		Asserts.notNull(companyAccount, StatusMsg.StatusMsg_301);
		Asserts.equals(companyAccount.getMarketingCooperative(), Constants.TRUE, StatusMsg.StatusMsg_1201);
		MarketingCooperative entity = marketingCooperativeMapper.getByCompidAndPartnerid(compid, partnerid);
		if (entity == null) {
			entity = new MarketingCooperative().setCompid(compid).setPartnerid(partnerid).setState(MarketingCooperativeState.VALID);
			entity.insert();
		} else {
			entity.setState(MarketingCooperativeState.VALID).updateById();
		}
		return entity;
	}

	public SmartResult<String> generateQrcode(BaseSimpleFormBean formBean) {
		int compid = formBean.getUserid();
		CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", compid));
		Asserts.notNull(companyAccount, StatusMsg.StatusMsg_302);
		Asserts.equals(companyAccount.getMarketingCooperative(), Constants.TRUE, StatusMsg.StatusMsg_1201);

		// If already have a qrcode, return it.
		if (StringUtil.isNotEmpty(companyAccount.getMarketingCooperativeQrcode())) {
			return SmartResult.success(companyAccount.getMarketingCooperativeQrcode());
		}

		// The img path of qrcode
		String uploadpath = uploadPathConfig.getUploadpath();
		String datePath = DateUtil.getString(DateUtil.nowDate(), DateUtil.FORMAT_STYLE_8);
		String qrcodePath = datePath + File.separator + "marketing_cooperative_" + compid;
		File file = new File(uploadpath, qrcodePath);
		try {
			String fileName = QrcodeUtil.encode(String.format(zddUrlConfig.getMarketingCooperativePartnerRegisterUrl(), compid), file.getAbsolutePath());
			qrcodePath = qrcodePath + File.separator + fileName;
			// Save img path to company account
			companyAccount.setMarketingCooperativeQrcode(qrcodePath).updateById();
			return SmartResult.success(qrcodePath);
		} catch (Exception e) {
			log.error("生成合销云二维码报错", e);
		}
		return SmartResult.ofOptFail();
	}

	public SmartResult<MarketingCooperativePartnerDto> listPartners(BaseSimpleFormBean<MarketingCooperativePartnerListFormBean> formBean) {
		MarketingCooperativePartnerListFormBean reqdata = formBean.getReqdata();
		int compid = formBean.getUserid();
		Page<MarketingCooperativePartnerDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		marketingCooperativeMapper.listByCompid(compid, reqdata.getName(), reqdata.getPhone(),0);
		return SmartResult.ofPage(page);
	}

	public SmartResult<MarketingCooperativeRecordDto> listCompanyRecords(
			BaseSimpleFormBean<MarketingCooperativeRecordListFormBean> formBean) {
		int compid = formBean.getUserid();
		MarketingCooperativeRecordListFormBean reqdata = formBean.getReqdata();
		Page<MarketingCooperativeRecordDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		marketingCooperativeRecordMapper.listByCompid(compid, reqdata.getPartnerName(), reqdata.getContactName(), reqdata.getCompanyNote(),
				reqdata.getState());
		return SmartResult.ofPage(page);
	}

	public void exportRecords(HttpServletResponse response, int compid, MarketingCooperativeRecordListFormBean reqdata) {
		List<MarketingCooperativeRecordDto> list = marketingCooperativeRecordMapper.listByCompid(compid, reqdata.getPartnerName(),
				reqdata.getContactName(), reqdata.getCompanyNote(), reqdata.getState());
		EasyExcelUtil.download(response, "客户需求", MarketingCooperativeRecordDto.class, list);
	}

	public SmartResult<MarketingCooperativeRecordDto> listPartnerRecords(
			BaseSimpleFormBean<MarketingCooperativeRecordListFormBean> formBean) {
		int compid = formBean.getUserid();
		MarketingCooperativeRecordListFormBean reqdata = formBean.getReqdata();
		Page<MarketingCooperativeRecordDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		marketingCooperativeRecordMapper.listByPartnerid(compid, reqdata.getContactName(), reqdata.getCompanyNote(), reqdata.getState());
		return SmartResult.ofPage(page);
	}

	public SmartResult saveCompanyNote(BaseSimpleFormBean<MarketingCooperativeNoteFormBean> formBean) {
		MarketingCooperativeNoteFormBean reqdata = formBean.getReqdata();
		int id = reqdata.getId();
		String companyNote = reqdata.getCompanyNote();
		new MarketingCooperativeRecord().setId(id).setCompanyNote(companyNote).updateById();
		return SmartResult.success();
	}

	public SmartResult verifyRecord(BaseSimpleFormBean<VerifyMarketingCooperativeRecordFormBean> formBean) {
		VerifyMarketingCooperativeRecordFormBean reqdata = formBean.getReqdata();
		int id = reqdata.getId();
		int state = reqdata.getState();
		BigDecimal brokerage = reqdata.getBrokerage();
		String brokerageNote = reqdata.getBrokerageNote();

		MarketingCooperativeRecord record = new MarketingCooperativeRecord().selectById(id);
		Asserts.notNull(record, StatusMsg.StatusMsg_1202);
		if (!NumberUtil.intIn(record.getState(), MarketingCooperativeRecordState.APPLIED, MarketingCooperativeRecordState.VERIFY_FAILED)) {
			return SmartResult.fail(StatusMsg.StatusMsg_1203);
		}

		record.setState(state).setBrokerage(brokerage).setBrokerageNote(brokerageNote).setVerifytime(new Date()).updateById();
		return SmartResult.success();
	}

	public SmartResult dealRecord(BaseSimpleFormBean<DealMarketingCooperativeRecordFormBean> formBean) {
		DealMarketingCooperativeRecordFormBean reqdata = formBean.getReqdata();
		List<Integer> ids = reqdata.getIds();
		String receipt = reqdata.getReceipt();
		for (Integer id : ids) {
			MarketingCooperativeRecord record = new MarketingCooperativeRecord().selectById(id);
			if (record == null) continue;
			if (!NumberUtil.equals(record.getState(), MarketingCooperativeRecordState.VERIFIED)) continue;

			record.setState(MarketingCooperativeRecordState.DEALED).setReceipt(receipt).setDealtime(new Date()).updateById();
			// 成交后发消息给合伙人
			wxPartnerMessageService.notifyMarketingCooperativeRecordDealed(record);
		}
		return SmartResult.success();
	}

	public SmartResult<MarketingCooperativeBrokerageDto> countRecordBrokerage(BaseSimpleFormBean formBean) {
		int partnerid = formBean.getUserid();
		MarketingCooperativeBrokerageDto dto = marketingCooperativeRecordMapper.countBrokerage(partnerid);
		return SmartResult.success(dto);
	}


	public SmartResult<MarketingCooperativePosterConfigDto> listPosterConfigs(BaseSimpleFormBean formBean) {
		Asserts.equals(formBean.getIdtype(), UserType.COMPANY);
		Page<MarketingCooperativePosterConfigDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		marketingCooperativePosterConfigMapper.listByCompid(formBean.getUserid());
		return SmartResult.ofPage(page);
	}

	public SmartResult<MarketingCooperativePosterConfigDto> listCompanyPosterConfigs(BaseSimpleFormBean<Integer> formBean) {
		Asserts.equals(formBean.getIdtype(), UserType.PARTNER);
		Integer compid = formBean.getReqdata();
		Page<MarketingCooperativePosterConfigDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		marketingCooperativePosterConfigMapper.listByCompid(compid);
		return SmartResult.ofPage(page);
	}

	public SmartResult<GeneratePartnerPosterDto> generatePartnerPoster(BaseSimpleFormBean<GeneratePartnerPosterFormBean> formBean) {
		Asserts.equals(formBean.getIdtype(), UserType.PARTNER);

		GeneratePartnerPosterFormBean reqdata = formBean.getReqdata();
		int posterConfigId = reqdata.getPosterConfigId();
		MarketingCooperativePosterConfig posterConfig = marketingCooperativePosterConfigMapper.selectById(
				posterConfigId);
		int partnerid = formBean.getUserid();
		String url = coreMarketingCooperativeService.generatePosterImg(partnerid, posterConfig);
		Asserts.notEmpty(url, StatusMsg.StatusMsg_1206);
		//保持不重复
		int i = marketingCooperativePartnerPosterMapper.deleteByFormId(partnerid,posterConfig.getCompid(),posterConfigId);

		MarketingCooperativePartnerPoster poster = new MarketingCooperativePartnerPoster().setPartnerid(
				partnerid).setPosterConfigId(posterConfigId).setCompid(posterConfig.getCompid()).setImgPath(url);
		poster.insert();

		GeneratePartnerPosterDto dto = marketingCooperativePartnerPosterMapper.generatePartnerPoster(poster.getId());
		return SmartResult.success(dto);
	}

	public SmartResult<MarketingCooperativePartnerPosterDto> listPartnerPosters(BaseSimpleFormBean formBean) {
		Asserts.equals(formBean.getIdtype(), UserType.PARTNER);
		Page<MarketingCooperativePartnerPosterDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		marketingCooperativePartnerPosterMapper.listByPartnerid(formBean.getUserid());
		return SmartResult.ofPage(page);
	}

	public SmartResult<MarketingCoorperativeCompanyFormDto> getPartnerPosterForm(BaseSimpleFormBean<PartnerPosterFormFormBean> formBean) {
		PartnerPosterFormFormBean reqdata = formBean.getReqdata();
		int posterConfigId = reqdata.getPosterConfigId();
		MarketingCooperativePosterConfig posterConfig = new MarketingCooperativePosterConfig().selectById(
				posterConfigId);
		Asserts.notNull(posterConfig, StatusMsg.StatusMsg_1207);

		MarketingCoorperativeCompanyFormDto formDto = marketingCooperativeCompanyFormMapper.getByFormId(posterConfig.getFormId());
		return SmartResult.success(formDto);
	}

	public SmartResult savePartnerMarketingCooperativeRecord(BaseSimpleFormBean<PartnerMarketingCooperativeRecordFormBean> formBean) {
		PartnerMarketingCooperativeRecordFormBean reqdata = formBean.getReqdata();
		Integer partnerid = reqdata.getPartnerid();
		PartnerAccount account = new PartnerAccount().selectOne(Condition.create().eq("partnerid", partnerid));
		Asserts.notNull(account, StatusMsg.StatusMsg_501);
		if(reqdata.getPosterConfigId() != null && reqdata.getPosterConfigId() != 0){
			//获取企业海报配置表中的企业id
			MarketingCooperativePosterConfig posterConfig = new MarketingCooperativePosterConfig().selectById(reqdata.getPosterConfigId());
			Asserts.notNull(posterConfig, StatusMsg.StatusMsg_1207);
			reqdata.setCompid(posterConfig.getCompid());
		}else if (reqdata.getFormId() != null && reqdata.getFormId() != 0){
			//获取企业表单配置表中的企业id
			MarketingCooperativeCompanyForm Form = new MarketingCooperativeCompanyForm().selectById(reqdata.getFormId());
			Asserts.notNull(Form, StatusMsg.StatusMsg_1207);
			reqdata.setCompid(Form.getCompid());
		}else {
			return SmartResult.fail(StatusMsg.StatusMsg_102);
		}


		MarketingCooperativeRecord record = reqdata.toEntity();
		if (record.insert()) {
			// 发送微信消息给胡晓峰
			wxPartnerMessageService.notifyPartnerApplyMarketingCooperativeRecord(record);
		}
		return SmartResult.success();
	}
	public SmartResult listPageForms(BaseSimpleFormBean<Integer> formBean) {
		Asserts.equals(formBean.getIdtype(), UserType.PARTNER);
		Integer compid = formBean.getReqdata();
		Page<MarketingCoorperativeCompanyFormDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		marketingCooperativeCompanyFormMapper.listByCompid(compid);
		return SmartResult.ofPage(page);
	}
	public SmartResult listPageFormsId(BaseSimpleFormBean<Integer> formBean) {
		Asserts.equals(formBean.getIdtype(), UserType.PARTNER);
		Integer formId = formBean.getReqdata();
		MarketingCoorperativeCompanyFormDto dto = marketingCooperativeCompanyFormMapper.getByFormId(formId);
		return SmartResult.success(dto);
	}
}
